﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.VisualBasic;

namespace ece750project
{
    
    enum PV_tree_enum
    {
        Visit_node=1,
        Appointment_node=2,
        Patient_node=3,
        dumy_node=4
    }
    struct PV_tree_type
    {
        public int ID;
        public PV_tree_enum node_type;
        public bool Original_Patient;
        public abc_ns.abc_class.visit_Struct Visit;
    }

    public struct DoctorMain_para_type
    {
        public int Doc_id;
        public int Staff_id;
        
    }
    public partial class DoctorMain : Form
    {

        public DoctorMain_para_type para;
        public bool View_Mode;

        public DoctorMain()
        {
            InitializeComponent();
        }

        public void Fill_doc_Patients(int Doc_ID)
        {
            PV_tree.Nodes.Clear();
            DataTable DT = DB_BusinessRules.Get_Doc_Patients(Doc_ID);
            TreeNode RootN = PV_tree.Nodes.Add("Patients");
            RootN.Tag = 0;

            for (int i = 0; i <= DT.Rows.Count - 1; i++)
            {
                string fn,ln;
                int pid;
                PV_tree_type PT = new PV_tree_type();
                
                pid=Convert.ToInt32 (DT.Rows[i]["person_id"]);
                fn=DT.Rows[i]["first_name"].ToString ();
                ln=DT.Rows[i]["last_name"].ToString ();
                PT.Original_Patient = Convert.ToBoolean( DT.Rows[i]["Original"]);
                PT.ID = pid;
                PT.node_type = PV_tree_enum.Patient_node;

                
                TreeNode TNode = RootN.Nodes.Add("p" + pid, ln + ", " + fn);
                TNode.Tag = PT;
                if (PT.Original_Patient == false)
                {TNode.ForeColor = Color.Blue;}
                else
                {

                    DataTable DTP = DB_BusinessRules.get_patient_recent_appointments(pid, Doc_ID);
                    if (DTP != null && DTP.Rows.Count>0)
                    {
                        PV_tree_type VT = new PV_tree_type();
                        TreeNode APNode = TNode.Nodes.Add("AP" + pid ,"Appointments");
                        VT.node_type = PV_tree_enum.dumy_node;
                        APNode.Tag = VT;
                        APNode.ForeColor = Color.Blue;

                        for (int ii = 0; ii <= DTP.Rows.Count - 1; ii++)
                        {
                            DateTime SDate = Convert.ToDateTime(DTP.Rows[ii]["service_Date"]);
                            DateTime STime = Convert.ToDateTime(DTP.Rows[ii]["service_Time"]);
                            int schedule_ID = Convert.ToInt16(DTP.Rows[ii]["schedule_id"]);
                            string title = "Appointment On " + SDate.ToLongDateString() + ", " + STime.ToShortTimeString();
                            PV_tree_type VT2 = new PV_tree_type();
                            TreeNode TTNode = APNode.Nodes.Add("AP" + schedule_ID, title);
                            VT2.node_type = PV_tree_enum.Appointment_node;
                            VT2.ID = schedule_ID;
                            VT2.Original_Patient = true;
                            TTNode.Tag = VT2;
                        }
                    }
                }

				
				if(PT.Original_Patient==true)
				{
	                DataTable DT2 = DB_BusinessRules.Get_Patient_visits(pid, Doc_ID);
	                if (DT2 != null && DT2.Rows.Count > 0)
	                {
	                    PV_tree_type VTD = new PV_tree_type();
	                    TreeNode VSNode = TNode.Nodes.Add("VS" + pid, "Visits");
	                    VTD.node_type = PV_tree_enum.dumy_node;
	                    VSNode.Tag = VTD;
	                    VSNode.ForeColor = Color.Blue;
	
	                    for (int ii = 0; ii <= DT2.Rows.Count - 1; ii++)
	                    {
	                        int vid;
	                        string title;
	                        PV_tree_type VT = new PV_tree_type();
	                        DateTime vdate;
	                        vid = Convert.ToInt16(DT2.Rows[ii]["visit_id"].ToString());
	                        vdate = Convert.ToDateTime(DT2.Rows[ii]["service_date"]);
	                        title = DT2.Rows[ii]["visit_type"].ToString();
	                        title = title == "0" ? "New Visit On : " : "Follow Up On : ";
	                        VT.ID = vid; VT.node_type = PV_tree_enum.Visit_node;
	                        VT.Original_Patient = PT.Original_Patient;
	                        TreeNode TTNode = VSNode.Nodes.Add("v" + vid, title + vdate.ToLongDateString());
	                        TTNode.Tag = VT;
	                        if (VT.Original_Patient == false) TTNode.ForeColor = Color.Blue;
	                    }
	                }
				}
				else
				{
	                DataTable DT2 = DB_BusinessRules.get_patient_visit_notOriginal (pid, Doc_ID);
	                if (DT2 != null && DT2.Rows.Count > 0)
	                {
	                    PV_tree_type VTD = new PV_tree_type();
	                    TreeNode VSNode = TNode.Nodes.Add("VS" + pid, "Visits");
	                    VTD.node_type = PV_tree_enum.dumy_node;
	                    VSNode.Tag = VTD;
	                    VSNode.ForeColor = Color.Blue;
	
	                    for (int ii = 0; ii <= DT2.Rows.Count - 1; ii++)
	                    {
	                        int vid;
	                        string title;
	                        PV_tree_type VT = new PV_tree_type();
	                        DateTime vdate;
	                        vid = Convert.ToInt16(DT2.Rows[ii]["visit_id"].ToString());
	                        vdate = Convert.ToDateTime(DT2.Rows[ii]["service_date"]);
	                        title = DT2.Rows[ii]["visit_type"].ToString();
	                        title = title == "0" ? "New Visit On : " : "Follow Up On : ";
	                        VT.ID = vid; VT.node_type = PV_tree_enum.Visit_node;
	                        VT.Original_Patient = PT.Original_Patient;
	                        TreeNode TTNode = VSNode.Nodes.Add("v" + vid, title + vdate.ToLongDateString());
	                        TTNode.Tag = VT;
	                        if (VT.Original_Patient == false) TTNode.ForeColor = Color.Blue;
	                    }
	                }
					
				}
            }
            GC.Collect();
            PV_tree.Nodes[0].Expand();
        }

        public void Fill_visit_notes(int visit_id)
        {
            visit_notes_list.Items.Clear();

            DataTable DT = DB_BusinessRules.Get_visit_Notes(visit_id);
            for (int i = 0; i <= DT.Rows.Count - 1; i++)
            {
                abc_ns.abc_class.visit_notes_Struct PS_TAG = new abc_ns.abc_class.visit_notes_Struct();
                abc_ns.abc_class.visit_notes_Struct_Load (ref PS_TAG, ref DT, i);

                ListViewItem IT = visit_notes_list.Items.Add(PS_TAG.note);
                IT.SubItems.Add(PS_TAG.TimeStamp.ToShortDateString());
                IT.Tag = PS_TAG;
            }

        }
        public void Fill_visit_prescriptions(int visit_id)
        {
            prescription_list.Items.Clear();

            DataTable DT = DB_BusinessRules.Get_visit_prescriptions(visit_id);
            for (int i = 0; i <= DT.Rows.Count - 1; i++)
            {
                abc_ns.abc_class.prescription_Struct PS_TAG = new abc_ns.abc_class.prescription_Struct();
                abc_ns.abc_class.prescription_Struct_Load(ref PS_TAG, ref DT,i);

                ListViewItem IT = prescription_list.Items.Add(PS_TAG.perscription);
                IT.SubItems.Add(PS_TAG.description);
                IT.SubItems.Add(PS_TAG.issue_Date.ToShortDateString());
                IT.SubItems.Add(PS_TAG.valid_untill.ToShortDateString());
                IT.Tag = PS_TAG;
            }

        }

        public void Fill_Health_indecations()
        {
            cmpHealthIndecation.Items.Clear();

            DataTable DT = DB_BusinessRules.Get_Health_indecations();
            for (int i = 0; i <= DT.Rows.Count - 1; i++)
            {
                string s = DT.Rows[i]["status_id"].ToString() + ":" + DT.Rows[i]["health_indication"].ToString();
                cmpHealthIndecation.Items.Add(s);

            }
        }

        public void Show_visit_info(int visit_id)
        {
            DataTable DT = DB_BusinessRules.Get_visit(visit_id);
            if (DT.Rows.Count > 0)
            {
                txtreason.Text = DT.Rows[0]["reason"].ToString();
                txtdiagonosis.Text = DT.Rows[0]["diagonosis"].ToString();
                cmp_visit_type.SelectedIndex = Convert.ToInt16 (DT.Rows[0]["visit_type"]);
                int index =Convert.ToInt16 ( DT.Rows[0]["health_indication"]);
                cmpHealthIndecation.SelectedIndex =index-1;

            }
        }

        private void DoctorMain_Load(object sender, EventArgs e)
        {
            lbldoctor_name.Text = DB_BusinessRules.get_person_name(para.Doc_id);
            if (View_Mode == true)
            {
                lbldoctor_name.Text += "\n(Read Only)";
                btn_grant_staff.Enabled = false;
            }
            Fill_doc_Patients(para.Doc_id);
            Fill_Health_indecations();
            Fill_docs_servicess(para.Doc_id);
        }


        private void permitDoctorToolStripMenuItem_Click(object sender, EventArgs e)
        {
            abc_app.permitDoctors_para.Doc_id = para.Doc_id;

            PV_tree_type PVT = (PV_tree_type)PV_tree.SelectedNode.Tag;

            if (PVT.node_type == PV_tree_enum.Visit_node)
            {
                abc_app.permitDoctors_para.Visit_id = PVT.ID;
                PV_tree_type PVT2 = (PV_tree_type)PV_tree.SelectedNode.Parent.Tag;
                abc_app.permitDoctors_para.Patient_id = PVT2.ID;
            }
            else if (PVT.node_type == PV_tree_enum.Patient_node)
            {
                abc_app.permitDoctors_para.Visit_id = -1;
                abc_app.permitDoctors_para.Patient_id = PVT.ID;
            }

            PermitDoctors form1 = new PermitDoctors();
            form1.ShowDialog();

        }

        private void PV_tree_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {

                if (PV_tree.SelectedNode == null) return;
                if (PV_tree.SelectedNode.Tag.ToString() == "0") return;
                PV_tree_type PVT = (PV_tree_type)PV_tree.SelectedNode.Tag;
                if (PVT.Original_Patient == false) return;

                if (PVT.node_type ==PV_tree_enum.Visit_node)
                {
                    if (View_Mode == false)
                        Menu_Visits.Show(PV_tree, e.Location);
                }
                else if (PVT.node_type==PV_tree_enum.Patient_node)
                {
                    if (View_Mode == false)
                        Menu_patient.Show(PV_tree, e.Location);
                }
                else if (PVT.node_type == PV_tree_enum.Appointment_node)
                {
                    if (View_Mode == false)
                        MMenu_add_vist.Show(PV_tree, e.Location);
                }

            }

        }

        private void PV_tree_DoubleClick(object sender, EventArgs e)
        {
            if (PV_tree.SelectedNode == null) return;
            if (PV_tree.SelectedNode.Tag.ToString()== "0") return;
            PV_tree_type PVT = (PV_tree_type)PV_tree.SelectedNode.Tag;
            if (PVT.node_type ==PV_tree_enum.Visit_node)
            {
                Show_visit_info(PVT.ID);
                Fill_visit_notes(PVT.ID);
                Fill_visit_prescriptions(PVT.ID);
            }
            else if (PVT.node_type == PV_tree_enum.Appointment_node)
            {
                Interaction.Beep();
            }


        }

        private void prescription_list_MouseUp(object sender, MouseEventArgs e)
        {

            if (e.Button == MouseButtons.Right)
            {
                if (PV_tree.SelectedNode == null) return;
                PV_tree_type PVT = (PV_tree_type)PV_tree.SelectedNode.Tag;
                if (PVT.node_type ==PV_tree_enum.Visit_node)
                {
                    if(View_Mode==false)
                        Menu_prescriptions.Show(prescription_list, e.Location);
                }

                
    
            }

        }

        public void Fill_docs_service_timeslots(int service_id, int doc_id)
        {
            doctor_time_slots.Items.Clear();
            DataTable DT = DB_BusinessRules.get_doc_service_schedule(service_id, doc_id);
            if (DT == null) return;
            for (int i = 0; i <= DT.Rows.Count - 1; i++)
            {
                string PatientName = "", Staff_name = "", txtStatus = "";
                TimeSlots_type TS_Tag = new TimeSlots_type();
                TS_Tag.D_ID = doc_id;
                TS_Tag.S_ID = service_id;
                TS_Tag.Sechedual_ID = Convert.ToInt32(DT.Rows[i]["schedule_id"]);
                TS_Tag.P_ID = DT.Rows[i]["patient_id"] == DBNull.Value ? -1 : Convert.ToInt32(DT.Rows[i]["patient_id"]);

                TS_Tag.status = Convert.ToInt16(DT.Rows[i]["status"]);
                TS_Tag.SDate = Convert.ToDateTime(DT.Rows[i]["service_date"]);
                TS_Tag.STime = Convert.ToDateTime(DT.Rows[i]["service_time"]);
                TS_Tag.Length = Convert.ToInt16(DT.Rows[i]["length"]);

                PatientName = DT.Rows[i]["patient_name"].ToString();
                Staff_name = DT.Rows[i]["staff_name"].ToString();
                if (TS_Tag.status == 1) txtStatus = "Available";
                if (TS_Tag.status == 2) txtStatus = "Boocked";
                if (TS_Tag.status == 3) txtStatus = "Canceld";
                if (TS_Tag.status == 4) txtStatus = "Confirmed";


                ListViewItem IT = doctor_time_slots.Items.Add(TS_Tag.SDate.ToLongDateString());
                IT.SubItems.Add(TS_Tag.STime.ToShortTimeString());
                IT.SubItems.Add(TS_Tag.Length.ToString() + " Minutes");
                IT.SubItems.Add(txtStatus);
                IT.SubItems.Add(PatientName);
                IT.SubItems.Add(Staff_name);
                IT.Tag = TS_Tag;

                if (TS_Tag.status == 1) IT.ForeColor = Color.Green;
                if (TS_Tag.status == 2) IT.ForeColor = Color.Red;
                if (TS_Tag.status == 3) IT.ForeColor = Color.GreenYellow;
                if (TS_Tag.status == 4) IT.ForeColor = Color.Blue;
            }
            GC.Collect();
        }

        public void Fill_docs_servicess(int doc_id)
        {
            listServices.Items.Clear();
            DataTable DT = DB_BusinessRules.get_doc_services_list(doc_id);
            if (DT == null) return;
            for (int i = 0; i <= DT.Rows.Count - 1; i++)
            {
                int Service_Id;
                string serviceName;

                Service_Id = Convert.ToInt16(DT.Rows[i]["service_id"]);
                serviceName = DT.Rows[i]["service_name"].ToString();

                ListViewItem IT = listServices.Items.Add(serviceName);
                IT.Tag = Service_Id;
            }
            GC.Collect();
        }

        private void visit_notes_list_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (PV_tree.SelectedNode == null) return;
                PV_tree_type PVT = (PV_tree_type)PV_tree.SelectedNode.Tag;
                if (PVT.node_type ==PV_tree_enum.Visit_node)
                {
                    if (View_Mode == false)
                        Menu_Visit_notes.Show(visit_notes_list, e.Location);
                }

                

            }

        }

        private void DoctorMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        private void addPrescriptionToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ADD_prescription frm = new ADD_prescription();
            frm.ShowDialog();
            if (abc_app.AddPrescription_para.Cancled == true)
            {
                Interaction.Beep();
                return;
            }
            PV_tree_type PVT_Tag =(PV_tree_type ) PV_tree.SelectedNode.Tag;
            DB_BusinessRules.add_prescription(PVT_Tag.ID,abc_app.AddPrescription_para.title ,abc_app.AddPrescription_para.Details
                ,abc_app.AddPrescription_para.SDate);
            Fill_visit_prescriptions(PVT_Tag.ID);
        }

        private void addVisitNoteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AddNotes frm = new AddNotes();
            frm.ShowDialog();
            if (abc_app.AddNote_para.Cancled == true)
            {
                Interaction.Beep();
                return;
            }

            string Note = abc_app.AddNote_para.Note;
            PV_tree_type PVT_Tag = (PV_tree_type)PV_tree.SelectedNode.Tag;
            DB_BusinessRules.add_visit_notes (PVT_Tag.ID,Note);
            Fill_visit_notes(PVT_Tag.ID);
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            DoctorMain_Load(sender, e);
        }

        private void schedule_date_DateChanged(object sender, DateRangeEventArgs e)
        {
           
        }

        /*public void Fill_doc_sechdule(int doc_id,DateTime service_date_var)
        {
            ScheduleVewList.Items.Clear();

            DataTable DT = DB_BusinessRules.get_doc_schedule(doc_id,service_date_var);
            for (int i = 0; i <= DT.Rows.Count - 1; i++)
            {
                int Sechdule_id = Convert.ToInt32(DT.Rows[i]["schedule_id"]);
                DateTime SD = Convert.ToDateTime(DT.Rows[i]["service_date"]);
                DateTime ST = Convert.ToDateTime(DT.Rows[i]["service_time"]);
                string  Status = DT.Rows[i]["status"].ToString();
                string Fname = DT.Rows[i]["first_name"].ToString();
                string Lname = DT.Rows[i]["last_name"].ToString();
                Status = Status.Replace("1", "Open"); Status = Status.Replace("2", "Boocked");
                Status = Status.Replace("3", "Canceled"); Status = Status.Replace("3", "Reserved");

                ListViewItem IT = ScheduleVewList.Items.Add(SD.ToLongDateString());
                IT.SubItems.Add(ST.ToShortTimeString());
                IT.SubItems.Add(Status);
                IT.SubItems.Add(Lname+", " + Fname);
                IT.Tag = Sechdule_id;
            }

        }*/

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            Fill_docs_service_timeslots(1, para.Doc_id);
        }

        public UInt16 Search_TreeNodes(string txt, TreeNode N)
        {
	        UInt16 functionReturnValue = default(UInt16);
	        //TreeNode subN = default(TreeNode);

	        if (string.IsNullOrEmpty(txt)) {
		        // Clear  All Nodes
		        foreach (TreeNode subN in N.Nodes) {
			        if (subN.Nodes.Count > 0) {
				        functionReturnValue += Search_TreeNodes(txt, subN);
			        }
			        // here put the code to process each node
			        subN.ForeColor = Color.Black;
			        subN.BackColor = Color.White;
		        }
		        return 1;
	        }

	        // Go Here if there are some things to search
            foreach (TreeNode subN in N.Nodes)
            {
		        if (subN.Nodes.Count > 0) {
			        functionReturnValue += Search_TreeNodes(txt, subN);
		        }
		        // here put the code to process each node
		        if (subN.Text.Contains(txt) == true) {
			        subN.ForeColor = Color.Red;
			        subN.BackColor = Color.PaleTurquoise;
			        subN.EnsureVisible();
			        functionReturnValue += 1;
		        } else {
			        subN.ForeColor = Color.Black;
			        subN.BackColor = Color.White;
		        }
	        }
	        return functionReturnValue;
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (PV_tree.Nodes.Count == 0)
                return;
            if (Search_TreeNodes(textBox1.Text, PV_tree.Nodes[0]) > 0)
            {
                textBox1.BackColor = Color.White;
            }
            else
            {
                textBox1.BackColor = Color.PaleVioletRed;
                Interaction.Beep();
            }
        }

        private void listServices_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void listServices_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            try
            {
                int S_ID = (int)listServices.SelectedItems[0].Tag;
                Fill_docs_service_timeslots(S_ID,para.Doc_id);

            }
            catch(Exception ex)
            {
                return;
            }
        }

        private void PV_tree_AfterSelect(object sender, TreeViewEventArgs e)
        {

        }

        private void btnAdd_visit_Click(object sender, EventArgs e)
        {
            bool valid=true;
            if (cmp_visit_type.SelectedIndex == -1) valid = false;
            if (cmpHealthIndecation.SelectedIndex  ==-1) valid = false;
            if(txtdiagonosis.Text == "") valid=false;
            if  (txtreason.Text == "") valid=false;

            if (valid == false)
            {
                Interaction.MsgBox("You must fill all fields correctlly", MsgBoxStyle.Exclamation, "input error");
                return;
            }

            try
            {
                int l = cmpHealthIndecation.Text.IndexOf(':');
                int healthinc = Convert.ToInt16(cmpHealthIndecation.Text.Substring(0, l));
                PV_tree_type PVT = (PV_tree_type)PV_tree.SelectedNode.Tag;
                DB_BusinessRules.add_visit(PVT.ID, cmp_visit_type.SelectedIndex, txtreason.Text, txtdiagonosis.Text, healthinc);
                btnAdd_visit.Enabled = false;
                PV_tree.Enabled = true;
            }
            catch (Exception ex)
            {
                Interaction.MsgBox(ex.Message + "\nThe Operation has aborted",MsgBoxStyle.Critical ,"Error");
            }
            


        }

        private void addVisitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            cmp_visit_type.SelectedIndex = 0;
            cmpHealthIndecation.Text = "";
            txtdiagonosis.Text = "";
            txtreason.Text = "";
            btnAdd_visit.Enabled = true;
            PV_tree.Enabled = false;

        }

        private void prescription_list_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (prescription_list.SelectedItems[0] == null) return;

            abc_ns.abc_class.prescription_Struct PS_TAG = (abc_ns.abc_class.prescription_Struct)prescription_list.SelectedItems[0].Tag;
            abc_app.AddPrescription_para.Show_mode = true;
            abc_app.AddPrescription_para.title = PS_TAG.perscription;
            abc_app.AddPrescription_para.Details = PS_TAG.description;
            abc_app.AddPrescription_para.SDate = PS_TAG.valid_untill;

            ADD_prescription frm = new ADD_prescription();
            frm.ShowDialog();


        }

        private void prescription_list_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void visit_notes_list_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (visit_notes_list.SelectedItems[0] == null) return;

            abc_ns.abc_class.visit_notes_Struct PS_TAG = (abc_ns.abc_class.visit_notes_Struct)visit_notes_list.SelectedItems[0].Tag;
            abc_app.AddNote_para.Show_mode = true;
            abc_app.AddNote_para.Note = PS_TAG.note;

            AddNotes frm = new AddNotes();
            frm.ShowDialog();

        }

        private void visit_notes_list_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btn_grant_staff_Click(object sender, EventArgs e)
        {
            grant_staff f = new grant_staff();
            f.para_info.doc_id=para.Doc_id;
            f.ShowDialog();

        }

    }
}
